package com.rbmh.network.utils;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExampleX {
    public static void main(String[] args) {
        String filePath = "C:\\Users\\Administrator\\Desktop\\XX县人社局工作介绍信某某.doc";

        // 方法1：直接使用专门的方法
//        System.out.println("=== 方法1：直接递增人事调干字号 ===");
//        WordDocumentHandlerX.incrementPersonnelDocumentNumber(filePath);

        // 方法2：使用通用方法，自定义正则表达式
//        System.out.println("\n=== 方法2：使用自定义正则表达式 ===");
//        String pattern = "新干人事调干字\\(2025\\)第(\\d{3})号";
//        WordDocumentHandlerX.incrementNumberInPattern(filePath, pattern);

        // 方法3：先查找所有匹配的内容，再选择要修改的
        System.out.println("\n=== 方法3：先查找再修改 ===");
        java.util.List<String> matches = WordDocumentHandlerX.findPatternInDocument(
                filePath, "新干人事调干字\\(2025\\)第\\d{3}号");

        System.out.println("找到的匹配项:");
        for (String match : matches) {
            System.out.println("- " + match);
        }

        if (!matches.isEmpty()) {
            WordDocumentHandlerX.incrementPersonnelDocumentNumber(filePath);
        }
    }

    /**
     * 更灵活的递增方法，支持不同的年份和前缀
     * @param filePath 文档路径
     * @param prefix 前缀，如 "新干人事调干字"
     * @param year 年份，如 2025
     */
    public static void incrementDocumentNumber(String filePath, String prefix, int year) {
        String pattern = prefix + "\\(" + year + "\\)第(\\d{3})号";
        WordDocumentHandlerX.incrementNumberInPattern(filePath, pattern);
    }

    /**
     * 支持自定义数字位数的版本
     * @param filePath 文档路径
     * @param pattern 正则表达式模式
     * @param digitCount 数字位数（用于补零）
     */
    public static void incrementNumberWithDigitFormat(String filePath, String pattern, int digitCount) {
        if (WordDocumentHandlerX.isDocxFormat(filePath)) {
            try (FileInputStream fis = new FileInputStream(filePath);
                 XWPFDocument document = new XWPFDocument(fis)) {

                boolean modified = false;
                Pattern regexPattern = Pattern.compile(pattern);

                // 在段落中查找并修改
                for (XWPFParagraph para : document.getParagraphs()) {
                    String text = para.getText();
                    Matcher matcher = regexPattern.matcher(text);

                    if (matcher.find()) {
                        String numberStr = matcher.group(1);
                        try {
                            int number = Integer.parseInt(numberStr);
                            int newNumber = number + 1;
                            String newNumberStr = String.format("%0" + digitCount + "d", newNumber);

                            String originalPattern = pattern.replace("(\\d{" + digitCount + "})", numberStr);
                            String replacement = originalPattern.replace(numberStr, newNumberStr);

                            String newText = text.replaceFirst(originalPattern, replacement);

                            for (int i = para.getRuns().size() - 1; i >= 0; i--) {
                                para.removeRun(i);
                            }
                            XWPFRun run = para.createRun();
                            run.setText(newText);

                            modified = true;
                            System.out.println("修改成功: " + text + " -> " + newText);

                        } catch (NumberFormatException e) {
                            System.err.println("无法解析数字: " + numberStr);
                        }
                    }
                }

                if (modified) {
                    try (FileOutputStream out = new FileOutputStream(filePath)) {
                        document.write(out);
                    }
                }
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
